﻿using BarcodeDelay;
using BarcodeDelay.bean;
using BarcodeDelay.FrameDecoder;
using BarcodeDelay.logHelp;
using BeetleX.FastHttpApi;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using RestSharp;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Web;

namespace JTParcrelHelper
{
    [Controller]
    class IndexController
    {
        public object Hello(string name)
        {
            System.Windows.Forms.MessageBox.Show(name);
            return "got";
            //return new { Hello = "hello" + name, Time = DateTime.Now };
        }



        [Post]
        [RequestMaxRPS(100)]
        [DefaultJsonResultFilter]
        public bool getWechatMsg(IHttpContext context)
        {
            int step = 0;
            string oriMsg = "";
            try
            {

                string contnet = context.Data.ToString();

                if (contnet.Contains("data") && contnet.Contains("body"))
                {
                    contnet = contnet.Substring(contnet.IndexOf("data") - 1);

                    if (contnet.Contains("MT_RECV_OTHER_APP_MSG"))
                    {
                        return true;
                    }
                    bool isFileType = false;

                    if (contnet.Contains("10698846594551886")
                        || contnet.Contains("0738969353566579")
                        || contnet.Contains("0743848086295603")
                        || contnet.Contains("10817532620802082")
                        || contnet.Contains("10963139559381089")
                        || contnet.Contains("10732235325746590")
                        || contnet.Contains("10876071207001972"))
                    {
                        return true;
                    }


                    if (contnet.Contains("\"type\""))
                    {
                        contnet = contnet.Substring(0, contnet.IndexOf("\"client_id\"") - 2);
                        contnet = Regex.Replace(contnet, @"[\r\n]", "");
                        contnet = contnet.TrimEnd().TrimEnd(',');
                        contnet = "{" + contnet + "}";

                        oriMsg = contnet;

                        //LogHelper.Instance.writeLog("解析到消息：" + contnet.ToString());

                        JObject dataRes = (JObject)JsonConvert.DeserializeObject(contnet);

                        JObject jsonObjRes = (JObject)dataRes["data"];
                        //LogHelper.Instance.writeLog("序列号成功");
                        JToken fromID = jsonObjRes["sender"];
                        JToken msgToken = jsonObjRes["content"];
                        JToken room_wxid = jsonObjRes["conversation_id"];
                        JToken to_wxid = jsonObjRes["receiver"];

                        JToken timestamp = jsonObjRes["send_time"];

                        

                        JArray atList = (JArray)jsonObjRes["at_list"];



                        JToken fileType = dataRes["type"];
                        if(fileType!=null&& fileType.ToString().Contains("WW_SEND_CHATROOM_AT_V2_MSG")&& fromID==null)
                        {
                            handleWechatMsgBean(dataRes);
                            return true;
                        }
                        step = 1;
                        string fileAttcatchName = "";
                        if (fileType != null)
                        {
                            if (fileType.ToString().Contains("WW_RECV_FILE_MSG"))
                            {
                                isFileType = true;
                                JObject cdnObj = (JObject)jsonObjRes["cdn"];
                                JToken fieName = cdnObj["file_name"];
                                if (fieName != null && fieName.ToString().Length > 1)
                                {
                                    fileAttcatchName = fieName.ToString();
                                }
                            }
                        }
                        step = 2;
                        if (timestamp != null)
                        {
                            long ltimestamp = long.Parse(timestamp.ToString());
                            //DateTime tt = Convert.ToDateTime(timestamp.ToString() + "000");
                            DateTime dtSendTime = UtilityHelp.Instance.ConvertLongToDateTime(ltimestamp);

                            DateTime dtNow = System.DateTime.Now;

                            TimeSpan tsNow = new TimeSpan(System.DateTime.Now.Ticks);
                            TimeSpan tsDiff = dtNow - dtSendTime;
                            if (tsDiff.TotalMinutes > 36)
                            {
                                return true;
                            }
                        }

                       

                        WechatMsgBean wechatMsgBean = new WechatMsgBean();
                        wechatMsgBean.from = fromID.ToString();
                        wechatMsgBean.roomid = room_wxid.ToString();
                        if (msgToken != null)
                        {
                            wechatMsgBean.content = msgToken.ToString();
                        }

                        if (StoParams.Instance.replyWechat == fromID.ToString())
                        {
                            wechatMsgBean.isSelfSendMsg = "1";
                            FrameDecoderManager.Instance.ackTaskQue.Enqueue(wechatMsgBean);
                            return true;
                        }

                        if (atList != null && atList.Count > 0)
                        {
                            step = 3;
                            foreach (JObject dataAtUser in atList)
                            {
                                if (dataAtUser.ToString().Length > 5)
                                {
                                    wechatMsgBean.atUserList.Add(dataAtUser["user_id"].ToString());
                                }
                            }
                        }
                        step = 4;
                        if (isFileType)
                        {
                            if (fileAttcatchName != "")
                            {
                                wechatMsgBean.file = fileAttcatchName.ToString();

                            }
                        }

                        wechatMsgBean.isSuperWay = true;

                        //LogHelper.Instance.writeLog("入队列 "+contnet);
                        FrameDecoderManager.Instance.superTaskQue.Enqueue(wechatMsgBean);
                        return true;

                    }
                }
            }
            catch (Exception ex)
            {
                LogHelper.Instance.writeLog("解析消息出错："+ ex.ToString() + ex.StackTrace.ToString() + "step=" + step.ToString()+"orimsg="+ oriMsg);
            }



            //curData = context.Data.GetObject("data", Type.);


            //System.Windows.Forms.MessageBox.Show(context.Data.ToString());


            return false;
        }


        private void handleWechatMsgBean(JObject dataRes)
        {
            int step = 0;
            bool isFileType = false;
            try
            {
                JToken fileType = dataRes["type"];
                if(fileType==null)
                {
                    LogHelper.Instance.writeLog("解析消息出错：" + dataRes.ToString());
                    return;
                }
         
                JObject jsonObjRes = (JObject)dataRes["data"];

                //LogHelper.Instance.writeLog("序列号成功");
                JToken fromID = jsonObjRes["sender"];
                JToken msgToken = jsonObjRes["content"];
                JToken room_wxid = jsonObjRes["conversation_id"];
                JToken to_wxid = jsonObjRes["receiver"];

                JToken timestamp = jsonObjRes["send_time"];

                JArray atList = (JArray)jsonObjRes["at_list"];
                step = 1;
                string fileAttcatchName = "";
                if (fileType != null)
                {
                    if (fileType.ToString().Contains("WW_RECV_FILE_MSG"))
                    {
                        isFileType = true;
                        JObject cdnObj = (JObject)jsonObjRes["cdn"];
                        JToken fieName = cdnObj["file_name"];
                        if (fieName != null && fieName.ToString().Length > 1)
                        {
                            fileAttcatchName = fieName.ToString();
                        }
                    }
                }
                step = 2;
                if (timestamp != null)
                {
                    long ltimestamp = long.Parse(timestamp.ToString());
                    //DateTime tt = Convert.ToDateTime(timestamp.ToString() + "000");
                    DateTime dtSendTime = UtilityHelp.Instance.ConvertLongToDateTime(ltimestamp);

                    DateTime dtNow = System.DateTime.Now;

                    TimeSpan tsNow = new TimeSpan(System.DateTime.Now.Ticks);
                    TimeSpan tsDiff = dtNow - dtSendTime;
                    if (tsDiff.TotalMinutes > 36)
                    {
                        return;
                    }
                }

                WechatMsgBean wechatMsgBean = new WechatMsgBean();

                if (fileType.ToString()== "WW_SEND_CHATROOM_AT_V2_MSG"&& fromID==null)
                {
                    JObject jsonObjData = (JObject)dataRes["data"];
                    JObject jsonObjMsgData = (JObject)jsonObjData["msg_data"];
                    fromID = jsonObjMsgData["sender"];
                    msgToken = jsonObjMsgData["content"];
                    room_wxid = jsonObjMsgData["roomid"];
                    to_wxid = jsonObjMsgData["receiver"];
                    timestamp = jsonObjMsgData["sendtime"];

                    wechatMsgBean.from = fromID.ToString();
                    wechatMsgBean.roomid = room_wxid.ToString();
                    if(!wechatMsgBean.roomid.StartsWith("R:"))
                    {
                        wechatMsgBean.roomid = "R:" + wechatMsgBean.roomid;
                    }
                    wechatMsgBean.isSuperWay = true;
                    wechatMsgBean.isAtMsg = true;
                    if(wechatMsgBean.from==StoParams.Instance.replyWechat)
                    {
                        FrameDecoderManager.Instance.superTaskQue.Enqueue(wechatMsgBean);
                    }
                    


                }
                

            }
            catch(Exception ex)
            {

            }
        }


        [Post]
        [RequestMaxRPS(100)]
        [DefaultJsonResultFilter]
        public bool getQQMsg(IHttpContext context)
        {
            try
            {
                string contnet = HttpUtility.UrlDecode(context.Data.ToString()).ToString();
       
                contnet = contnet.Replace("body=", "");
                contnet = contnet.TrimEnd('\n');
                contnet = contnet.TrimEnd('\r');
                JObject jsonObjResTp = (JObject)JsonConvert.DeserializeObject(contnet);
                WechatMsgBean wechatMsgBean = new WechatMsgBean();

                //if(contnet.ToString().Contains("JT"))
                {                    
                    string roomID = jsonObjResTp["MQ_fromID"].ToString();
                    string msgContent = jsonObjResTp["MQ_msg"].ToString();
                    string fromQQ= jsonObjResTp["MQ_fromQQ"].ToString();

                    string robotQQ = jsonObjResTp["MQ_robot"].ToString();
                    if(fromQQ== robotQQ)
                    {
                        return true;
                    }
                    if(!UtilityHelp.Instance.isValidQQMsg(msgContent))
                    {
                        return true;
                    }
                    
                    wechatMsgBean.content = msgContent.ToString();
                    wechatMsgBean.from = fromQQ.ToString();
                    wechatMsgBean.roomid = roomID.ToString();
                    wechatMsgBean.isQQ = true;
                    wechatMsgBean.isSuperWay = true;
                    wechatMsgBean.robotQQ = robotQQ;
                    //临时 todo
                    if(!FrameDecoderManager.Instance.htAllRooms.ContainsKey(wechatMsgBean.roomid))
                    {
                        FrameDecoderManager.Instance.htAllRooms[wechatMsgBean.roomid] = wechatMsgBean.roomid;
                        UtilityHelp.Instance.writeStaticBarcodeEx(wechatMsgBean.roomid);
                    }

                    //LogHelper.Instance.writeLog("解析到消息：" + msgContent.ToString());
                    FrameDecoderManager.Instance.superTaskQue.Enqueue(wechatMsgBean);

                }

            }
            catch (Exception ex)
            {

            }
            return true;



            //curData = context.Data.GetObject("data", Type.);


            //System.Windows.Forms.MessageBox.Show(context.Data.ToString());


            return false;
        }


    }
}
